package com.example.lz.downcount;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

/**
 * Created by lz on 16-7-2.
 */
public class DownCountView extends View {


    private Paint paintBg;
    private Paint paintNumber;
    private Paint paintSemicolon;

    private final float spacing_num = getResources().getDisplayMetrics().density * 6;
    private final float spacing_time = getResources().getDisplayMetrics().density * 26;
    private final float text_size = getResources().getDisplayMetrics().density * 18;
    private final float semicolonWidth = getResources().getDisplayMetrics().density * 4;

    private Rect[] rects = new Rect[6];
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.d("DownCountView", "handleMessage+DownCountView");
            invalidate();
            sendEmptyMessageDelayed(0, 1000);

        }
    };
    /**
     * 倒计时结束毫秒值
     */
    private long mEndTime;
    private Bitmap bitmapbg;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public DownCountView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public DownCountView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    public DownCountView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paintBg = new Paint();
        paintBg.setAntiAlias(true);


        paintNumber = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintNumber.setAntiAlias(true);
        paintNumber.setColor(Color.WHITE);
        paintNumber.setTextSize(text_size);
//        paintNumber.setStrokeWidth(3);
        paintNumber.setStyle(Paint.Style.STROKE);
        paintNumber.setTextAlign(Paint.Align.CENTER);

        paintSemicolon = new Paint();
        paintSemicolon.setAntiAlias(true);
        paintSemicolon.setColor(Color.BLACK);

        bitmapbg = BitmapFactory.decodeResource(getResources(), R.drawable.fangkuai);
    }

    public DownCountView(Context context) {
        super(context);
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        handler.removeCallbacksAndMessages(null);
//        bitmapbg.recycle();
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == View.VISIBLE) {
            handler.sendEmptyMessage(0);
        } else {
            handler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        float width = bitmapbg.getWidth() * 6 + spacing_time * 2 + spacing_num * 3 + getPaddingRight() + getPaddingLeft();
        float height = bitmapbg.getHeight() + getPaddingBottom() + getPaddingTop();
        setMeasuredDimension((int) width, (int) height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.TRANSPARENT);

        int width = bitmapbg.getWidth();
        int height = bitmapbg.getHeight();

        int[] time = computeTime(mEndTime);
        for (int i = 0; i < 6; i++) {
            int rectsLeft = (int) (i * width + (i + 1) / 2 * spacing_num + i / 2 * spacing_time);
            //计算六个数字显示边框到矩形,绘制背景
            rects[i] = new Rect(rectsLeft, 0, rectsLeft + width, height);
            canvas.drawBitmap(bitmapbg, rects[i].left, rects[i].top, paintBg);

            //绘制分号
            if (i > 0 && i % 2 == 0) {
                canvas.drawRect(
                        rects[i].left - spacing_time / 2 - semicolonWidth / 2,
                        height / 4,
                        rects[i].left - spacing_time / 2 + semicolonWidth / 2,
                        height / 4 + semicolonWidth, paintSemicolon);
                canvas.drawRect(
                        rects[i].left - spacing_time / 2 - semicolonWidth / 2,
                        height * 3 / 4 - semicolonWidth,
                        rects[i].left - spacing_time / 2 + semicolonWidth / 2,
                        height * 3 / 4, paintSemicolon);
            }

            //绘制数字
            Paint.FontMetricsInt metricsInt = paintNumber.getFontMetricsInt();
            int baseline = (rects[i].bottom + rects[i].top - metricsInt.bottom - metricsInt.top) / 2;
            canvas.drawText(String.valueOf(time[i]), rects[i].centerX(), baseline, paintNumber);
        }
    }


    private int[] computeTime(long end) {
        if (end == 0) {
            throw new RuntimeException("未设置倒计时结束时间");
        }
        int[] time = new int[6];
        long surplusSecond = (end - System.currentTimeMillis()) / 1000;
        time[5] = (int) (surplusSecond % 60 % 10);
        time[4] = (int) (surplusSecond % 60 / 10);

        time[3] = (int) (surplusSecond / 60 % 60 % 10);
        time[2] = (int) (surplusSecond / 60 % 60 / 10);

        time[1] = (int) (surplusSecond / 60 / 60 % 10);
        time[0] = (int) (surplusSecond / 60 / 60 / 10);


        return time;
    }

    public void setEndTime(long mEndTime) {
        this.mEndTime = mEndTime;
    }
}
